import { useReducer } from 'react'
import { ADDITEM, DELETEITEM, CHANGESTATUS, CHANGEALLSTATUS, DELETEALLDONE } from './config'
// 初始值
const defaultState = [];

// reducer函数
const reducer = (defaultState, action) => {
    let newState = [...defaultState];
    const { type, payload } = action;
    switch (type) {
        case ADDITEM:
            newState.unshift(payload);
            break;
        case DELETEITEM:
            newState = newState.filter(item => item.id !== payload);
            break;
        case CHANGESTATUS:
            newState.map(item => {
                if (item.id == payload) {
                    item.done = !item.done
                }
            })
            break;
        case CHANGEALLSTATUS:
            if (newState.length > 0) {
                newState.map(item => item.done = payload)
            }
            break;
        case DELETEALLDONE:
            if (newState.length > 0) {
                newState = newState.filter(item => item.done !== true);
            }
            break;
        default:
            break;
    }
    return newState;
}

const useList = () => {
    const [list, dispatch] = useReducer(reducer, defaultState);
    return [list, dispatch]
}

export default useList